package com.xxz.course;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.lang.annotation.Documented;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.sql.Time;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.prefs.PreferenceChangeEvent;
import  org.jsoup.*;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

public class ConvertActivity extends AppCompatActivity implements Runnable {
    private static final String TAG = "Rate";
    float dollarRate;
    float euroRate;
    float wonRate;
    TextView result;
    Handler handler;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main3);

        SharedPreferences sharedPreferences = getSharedPreferences("myrate", Activity.MODE_PRIVATE);
        //SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this); 另一种写法
        dollarRate = sharedPreferences.getFloat("dollar_rate", 0.1f);
        euroRate = sharedPreferences.getFloat("euro_rate", 0.2f);
        wonRate = sharedPreferences.getFloat("won_rate", 123.0f);

                Thread t = new Thread(this);
                t.start();


        handler = new Handler(Looper.myLooper()) {//匿名类定义对象
            @Override
            public void handleMessage(@NonNull Message msg) {
                if (msg.what == 5) {
                    Bundle bd = (Bundle) msg.obj;
                    dollarRate = bd.getFloat("美元",0.0f);
                    euroRate = bd.getFloat("欧元",0.0f);
                    wonRate = bd.getFloat("韩元",0.0f);
                    Log.i(TAG, "handleMessage: getMessage msg = " + dollarRate+euroRate+wonRate);
                    result = findViewById(R.id.result);
                }
                super.handleMessage(msg);
            }
        };//方法重写
    }

    private void openConfig() {
        Log.i(TAG, "open: 打开新窗口");
        Intent config = new Intent(this, TransportActivity.class);
        config.putExtra("dollar_key", dollarRate);
        config.putExtra("euro_key", euroRate);
        config.putExtra("won_key", wonRate);

        Log.i(TAG, "openOne: dollar_key=" + dollarRate);
        Log.i(TAG, "openOne: euro_key=" + euroRate);
        Log.i(TAG, "openOne: won_key=" + wonRate);
        //startActivity(config);
        startActivityForResult(config, 1);//此处整数任意，如1
    }

    public void click(View btn) {
        EditText input = findViewById(R.id.rmb);
        String s = input.getText().toString();
        if (s.length() == 0) {
            Toast.makeText(this, "请输入数据", Toast.LENGTH_LONG).show();
            return;
        }
        float inp = Float.parseFloat(s);
        float r = 0.0f;
        if (btn.getId() == R.id.dollor) {
            r = inp * dollarRate;
        } else if (btn.getId() == R.id.euro) {
            r = inp * euroRate;
        } else {
            r = inp * wonRate;
        }
        result = findViewById(R.id.result);
        result.setText("" + r);
    }

    public void open(View btn) {
        openConfig();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.rate, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        if (item.getItemId() == R.id.menu_set) {
            openConfig();
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1 && resultCode == 2) {
            Bundle bundle = data.getExtras();
            dollarRate = bundle.getFloat("key_dollar", 0.1f);
            euroRate = bundle.getFloat("key_euro", 0.1f);
            wonRate = bundle.getFloat("key_won", 0.1f);

            Log.i(TAG, "onActivityResult: dollarRate=" + dollarRate);
            Log.i(TAG, "onActivityResult: euroRate=" + euroRate);
            Log.i(TAG, "onActivityResult: wonRate=" + wonRate);

            //将新设置的汇率写到sp里
            SharedPreferences sharedPreferences = getSharedPreferences("myrate", Activity.MODE_PRIVATE);
            SharedPreferences.Editor editor = sharedPreferences.edit();
            editor.putFloat("dollar_rate", dollarRate);
            editor.putFloat("euro_rate", euroRate);
            editor.putFloat("won_rate", wonRate);
            editor.apply();
            Log.i(TAG, "onActivityResult: 数据已保存到sharedPreferences");
        }
    }

    @Override
    public void run() {
        Log.i(TAG, "run: run()......");
        for (int i = 1; i < 3; i++) {
            Log.i(TAG, "run: i=" + i);
        }

/*
        //获取网络数据
        try {
            URL url = new URL("https://www.usd-cny.com/bankofchina.htm");
            HttpURLConnection http = (HttpURLConnection) url.openConnection();
            InputStream in = http.getInputStream();
            String htm1 = inputStream2string(in);
            Log.i(TAG, "run htm1= " + htm1);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
 */     Bundle bundle = new Bundle();
        try {
            Document doc = Jsoup.connect("https://www.usd-cny.com/bankofchina.htm").get();//https标示加密传输
            Log.i(TAG,"run: title"+doc.title());
            Element table = doc.getElementsByTag("table").first();
            //Log.i(TAG,"run table="+table);
            Elements trs = table.getElementsByTag("tr");
            trs.remove(0);
            for(Element tr : trs){
                Elements tds = tr.getElementsByTag("td");
                Element t0 = tds.first();
                String hb = t0.text();
                if(tds.size()>0 && (hb.equals("美元") || hb.equals("欧元") || hb.equals("韩元"))){
                    //提取数据
                    Element td1 = tds.last();
                    String rate = td1.text();
                    Log.i(TAG,"run:"+td1.text());
                    float v = 100f / Float.parseFloat(rate);
                    bundle.putFloat(hb, v);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        //获取Msg对象，用于返回主线程
        Message msg = handler.obtainMessage(5);
         msg.obj = bundle;
        handler.sendMessage(msg);
    }

    private String inputStream2string(InputStream inputstream) throws IOException {
        final int buffersize = 10000000;
        final char[] buffer = new char[buffersize];
        final StringBuilder out = new StringBuilder();
        Reader in = new InputStreamReader(inputstream, "gb2312");
        while (true)
        {
            int rsz = in.read(buffer,0,buffer.length);
            if (rsz < 0)
                break;
            out.append(buffer,0,rsz);
            return out.toString();
        }
        return null;
    }
}